<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Category;
use App\Http\Requests\CategoryRequest;
use App\Wiki;
use Illuminate\Database\Eloquent\Builder;
class CategoriesController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Category $category)
    {
        return view('categories.create_and_edit', compact('category'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(CategoryRequest $request, Category $category)
    {
        $category->fill($request->all());

        $category->save();
        return response()->json($category);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show(Category $category)
    {
        // $category->load('articles');
        $articles = $category->articles->paginate(10);
        return view('categories.show', compact('category', 'articles'));
    }

    public function articles(Category $category, Request $request)
    {
        $order = $request->input('order', 'new');
        if(!$category->category_id) {
            $children = $category->children->pluck('id')->all();

            $wikis = Wiki::ordered($order)->whereHas('categories', function(Builder $query) use ($children) {
                $query->whereIn('categories.id', $children);
            })->paginate(10);
        } else {
            $wikis = $category->wikis()->ordered($order)->paginate(10);
        }

        return view('categories.wikis', compact('category', 'wikis'));
    }
    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
